package com.optitronics.controllers;

import java.util.ArrayList;
import java.util.Collection;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.optitronics.beans.Reseller;
import com.optitronics.service.ResellerService;
import com.optitronics.ui.ComboBoxSupport;
import com.optitronics.ui.ResellerForm;
import com.optitronics.util.OptitronicsConstants;
import com.optitronics.util.OptitronicsUtils;
import com.optitronics.validators.ResellerValidator;

@Controller
@RequestMapping({ "/resellers/new", "/resellers/{resellerId}/edit" })
@SessionAttributes("resellerForm")
public class ResellerFormController {

	protected Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private ResellerValidator resellerValidator;

	@Autowired
	private ResellerService resellerService;

	@RequestMapping(method = RequestMethod.GET, value = "/resellers/{resellerId}/edit")
	public String setupEditForm(@PathVariable("resellerId") Integer resellerId, Model model) {

		logger.info(OptitronicsUtils.getLoggerPrefix() + ": " + "Setup edit reseller form, resellerId: " + resellerId);

		Reseller reseller = null;
		if (OptitronicsUtils.isUserAdmin()) {
			reseller = Reseller.findReseller(resellerId);
		} else if (OptitronicsUtils.isUserReseller()) {
			reseller = Reseller.findResellerByEmail(OptitronicsUtils.getActiveUser());
		}

		ResellerForm formObject = new ResellerForm(reseller);
		model.addAttribute("resellerForm", formObject);
		referenceData(formObject, model);
		return "resellers/create";
	}

	private void referenceData(ResellerForm formObject, Model model) {

		Collection<ComboBoxSupport> statuses = new ArrayList<ComboBoxSupport>();

		statuses.add(new ComboBoxSupport(Reseller.STATUS_ACTIVE, messageSource.getMessage("label.reseller.status."
				+ Reseller.STATUS_ACTIVE, null, LocaleContextHolder.getLocale())));

		statuses.add(new ComboBoxSupport(Reseller.STATUS_INACTIVE, messageSource.getMessage("label.reseller.status."
				+ Reseller.STATUS_INACTIVE, null, LocaleContextHolder.getLocale())));
		statuses.add(new ComboBoxSupport(Reseller.STATUS_WAITING_FOR_ACTIVATION, messageSource.getMessage(
				"label.reseller.status." + Reseller.STATUS_WAITING_FOR_ACTIVATION, null,
				LocaleContextHolder.getLocale())));

		String titleKey = formObject.getId() == null ? "label.resellers.new" : "label.resellers.edit";
		model.addAttribute("titleKey", titleKey);

		model.addAttribute("statuses", statuses);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/resellers/new")
	public String setupNewForm(Model model) {

		logger.info("Setup new reseller form");
		ResellerForm formObject = new ResellerForm();
		model.addAttribute("resellerForm", formObject);

		referenceData(formObject, model);
		return "resellers/create";
	}

	@RequestMapping(method = RequestMethod.POST, value = { "/resellers/{resellerId}/edit", "/resellers/new" })
	public String processSubmit(Model model, @ModelAttribute("resellerForm") @Valid ResellerForm formObject,
			BindingResult result, SessionStatus status) {

		resellerValidator.validateForm(formObject, result);
		if (result.hasErrors()) {
			referenceData(formObject, model);
			return "resellers/create";
		} else {
			resellerService.saveReseller(formObject);
			status.setComplete();
			if (OptitronicsUtils.isUserAdmin()) {
				return "redirect:/resellers?page=1&size=" + OptitronicsConstants.PAGE_SIZE;
			} else if (OptitronicsUtils.isUserReseller()) {
				model.addAttribute("message", "label.data.saved");
				return "infoPage";
			} else {
				model.addAttribute("message", "label.reseller.registration.complete");
				return "infoPage";
			}
		}
	}

	@InitBinder
	public void setAllowedFields(WebDataBinder dataBinder) {
		dataBinder.setDisallowedFields("id");
	}

	public void setResellerValidator(ResellerValidator resellerValidator) {
		this.resellerValidator = resellerValidator;
	}

	public void setResellerService(ResellerService resellerService) {
		this.resellerService = resellerService;
	}

	public MessageSource getMessageSource() {
		return messageSource;
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
}
